//登录
import 'dart:convert';
import 'dart:io';
import 'package:date_format/date_format.dart';
import 'package:flutter_app/models/business.dart';
import 'package:flutter_app/models/getFriendList.dart';
import 'package:flutter_app/models/index.dart';
import 'package:flutter_app/models/register.dart';
//flutter packages pub run json_model
//flutter build apk
import 'Global.dart';
import '../models/login.dart';
import '../models/findFriendApl.dart';
import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
import 'package:flutter/material.dart';

class EA {
  // 在网络请求过程中可能会需要使用当前的context信息，比如在请求失败时
  // 打开一个新路由，而打开新路由需要context信息。
  EA([this.context]) {
    _options = Options(extra: {"context": context});
  }

  BuildContext context;
  Options _options;
  static Dio dio = new Dio();

  static String str = "http://81.69.46.100:9999";
  String url;

  static void init() {
    // 添加缓存插件
    //dio.interceptors.add(Global.netCache);
    // 设置用户token（可能为null，代表未登录）
    dio.options.headers[HttpHeaders.authorizationHeader] = Global.login.token;


  }

  // 登录接口，登录成功后返回用户信息
  Future<Login> login(int login, String pwd) async {
    String basic = 'Basic ' + base64.encode(utf8.encode('$login:$pwd'));
    Map<String,dynamic> formData = Map<String,dynamic>.from({
      "usrId":login,
      "usrPwd":pwd
    });
    url = str + '/login';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    //print(r.data.runtimeType.toString());
    return Login.fromJson(r.data);
  }

  // 注册接口
  Future<Register> register(int tel, String pwd) async {

    String basic = 'Basic ' + base64.encode(utf8.encode('$login:$pwd'));
    Map<String,dynamic> formData = Map<String,dynamic>.from({
      "usrTel":tel,
      "usrPwd":pwd
    });
    url = str + '/register';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    //登录成功后更新公共头（authorization），此后的所有请求都会带上用户身份信息
    //dio.options.headers[HttpHeaders.authorizationHeader] = basic;
    return Register.fromJson(r.data);
  }

  // 获取好友请求、好友列表、处理好友申请、发送好友申请
  Future<int> disposeFriendApl(int aplId, bool flag) async {
    List formData = [
      {
        "token": Global.login.token
      },
      {
        "flag": flag
      },
      {
        "usrId": aplId
      }
    ];
    url = str + '/addFriend';
    //print(formData);
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  Future<FindFriendApl> findFriendApl() async {
    List formData = [{
      "token": Global.login.token
    }];
    url = str + '/findApplyFriend';
    Response r = await dio.post(url, data:formData);
    Global.findFriendApl = FindFriendApl.fromJson(r.data);
    Global.findFriendApl.applyFriends != null ? Global.findFriendApl.applyFriends.forEach((element) {
      if(element['aplState'] == 500){
        Global.recentDisposeItem.add({
          "message": element['aplUser']['usrName'] + "请求添加您为好友",
          "Id": element['aplSelf'],
          "sort": 1
        });
      }
    }): null;
    Global.findFriendApl.myApplys!= null ? Global.findFriendApl.myApplys.forEach((element) {
      if(element['aplState'] == 501){
        Global.recentDisposeItem.add({
          "message": element['aplTarget']['usrName'] + "同意了您的好友请求",
          "aplId": element['aplId'],
          "sort": 3
        });
      }
      if(element['aplState'] == 502){
        Global.recentDisposeItem.add({
          "message": element['aplTarget']['usrName'] + "拒绝了您的好友请求",
          "aplId": element['aplId'],
          "sort": 3
        });
      }
    }): null;
    //print(r.data);
    return  Global.findFriendApl;
  }
  Future<GetFriendList> getFriendList() async {
    List formData = [{
      "token": Global.login.token
    }];
    url = str + '/allFriend';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return GetFriendList.fromJson(r.data);
  }
  Future<int> applyFriend(int usrId) async {
    List formData = (
        [
          {
            "token": Global.login.token,
          },
          {
            "usrId":usrId,
          }
        ]
    );
    url = str + '/applyFriend';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  Future<int> isReadFriend(int aplId) async {
    List formData = (
        [
          {
            "token": Global.login.token,
          },
          {
            "aplId":aplId,
          }
        ]
    );
    url = str + '/isReadFriend';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  //获取包揽申请、包揽列表、处理包揽申请、发送包揽申请
  Future<bool> disposeUndertakeApl(int pdAplId, bool flag) async {
    Map<String, dynamic> formData = Map<String, dynamic>.from({
      "token":Global.login.token,
      "pdAplId":pdAplId,
      "flag":flag,
    });
    url = str + '/requirement/agreePackage';
    //print(formData);
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['flag'];
  }
  Future<FindUndertakeApl> findUndertakeApl() async {
    Map<String, dynamic> formData = Map<String , dynamic>.from ({
          "token": Global.login.token
    });
    url = str + '/requirement/pdAplList';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    Global.findUndertakeApl = FindUndertakeApl.fromJson(r.data);
    Global.findUndertakeApl.allPdApplys != null ? Global.findUndertakeApl.allPdApplys.forEach((element) {
      if(element['aplState'] == 600){
        Global.recentDisposeItem.add({
          "message": element['aplUser']['usrName'] + "向您发送了工序包揽请求",
          "Id": element['aplId'],
          "aplTargetId": element['aplUsrId'],
          "sort": 2
        });
      }
    }):null;
    Global.findUndertakeApl.myPdApplys != null ? Global.findUndertakeApl.myPdApplys.forEach((element) {
      if(element['aplState'] == 601){
        Global.recentDisposeItem.add({
          "message": element['aplTarget']['usrName'] + "同意了您的包揽请求",
          "aplId": element['aplId'],
          "sort": 4
        });
      }
      if(element['aplState'] == 602){
        Global.recentDisposeItem.add({
          "message": element['aplTarget']['usrName'] + "拒绝了您的包揽请求",
          "aplId": element['aplId'],
          "sort": 4
        });
      }
    }):null;
    return Global.findUndertakeApl;
  }
  Future<int> applyUndertake(int targetId, int pjId, int pdId) async {
    List formData = [
      {
        "token": Global.login.token
      },
      {
        "targetId": targetId,
        "pjId": pjId,
        "pdId": pdId
      }
    ];
    //print(formData);
    url = str + '/requirement/packageOrderApplication';
    Response r = await dio.post(url, data:formData);
    return r.data['status'];
  }
  Future<FindUserProcedures> getUndertakeList() async {
    Map<String, dynamic> formData = Map<String , dynamic>.from ({
      "token": Global.login.token
    });
    url = str + '/requirement/myPackageProcedures';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return FindUserProcedures.fromJson(r.data);
  }
  Future<int> isReadProcedure(int aplId) async {
    List formData = (
        [
          {
            "token": Global.login.token,
          },
          {
            "aplId":aplId,
          }
        ]
    );
    url = str + '/isReadProcedure';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  // 获取当前业务总范围及用户业务范围
  Future<List> business() async {
    url = str + '/business/all';
    Response r = await dio.post(url);
    //print(r.data);
    //print(r.data.runtimeType.toString());
    //return Business.fromJson(r.data);
    return r.data;
  }
  Future<UsrBusiness> usrBusiness() async {
    List formData = [{
      "token": Global.login.token
    }];
    url = str + '/business/UserAll';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return UsrBusiness.fromJson(r.data);
    //return json.decode(r.data);
  }
  //修改用户资料
  Future<int> modifyUser() async {
    List formData = [
      {
      "token": Global.login.token
      },
      {
        "usrName":Global.login.user['usrName'],
        "usrPwd":Global.login.user['usrPwd'],
        "usrTel":Global.login.user['usrTel'],
        "usrAd":Global.login.user['usrAd']
      },
      {
        "business":Global.usrBusiness.business
      }
    ];
    url = str + '/modifyUser';
    Response r = await dio.post(url, data:formData);
    //print(r.data);

    return r.data['status'];
    //return UsrBusiness.fromJson(r.data);
    //return json.decode(r.data);
  }
  //查找好友
  Future<FindUser> findUser(int usrId) async {
    Map<String,dynamic> formData = Map<String,dynamic>.from(
        {
          "token": Global.login.token,
          "usrId":usrId,
        }
    );
    url = str + '/findUser';
    Response r = await dio.post(url, data:formData);
    print(r.data);
    return FindUser.fromJson(r.data);
  }
  //发布需求订单
  Future<int> releaseProject() async {
    List formData = [
      {
        "token": Global.login.token
      },
      {
        "pjName":Global.creatProject.pjName,
        "pjDeltime":formatDate(Global.creatProject.pjDeltime, [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss]),
        "pjProtime":formatDate(Global.creatProject.pjProtime, [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss]),
      },
    ];
    Global.creatProject.pd.forEach((item) {
      //print(item['pdDemand'].runtimeType);
      formData.add(
          {
            "pdName":item['pdName'],
            "pdDemand":int.parse(item['pdDemand']),
            "pdProtime":formatDate(item['pdProtime'], [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss]),
            "pdDeltime":formatDate(item['pdDeltime'], [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss]),
            "bsIds":item['bsIds']
          });
    });
    print(formData);
    url = str + '/requirement/create';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    //return r.data['status'];
    return r.data['status'];
    //return json.decode(r.data);
  }
  //首页工程、朋友圈工程、个人工程
  Future<MatchingFriend> matchingFriend() async {
    Map<String,dynamic> formData = Map<String,dynamic>.from(
        {
          "token": Global.login.token,
        }
    );
    url = str + '/requirement/matchingFriend';
    Response r = await dio.post(url, data:formData);
    int match;
    Set show = Set();
    List showCard = List();
    //print(r.data);
    Global.matchingFriend = MatchingFriend.fromJson(r.data);
    if(Global.matchingFriend.projects != null){
      Global.matchingFriend.projects.forEach((element) {
        List temp = List();
        show.clear();
        showCard.clear();
        element['project']['pjProtime'] = DateTime.parse(element['project']['pjProtime']);
        element['project']['pjDeltime'] = DateTime.parse(element['project']['pjDeltime']);
        element['project']['pjReltime'] = DateTime.parse(element['project']['pjReltime']);
        element['project']['procedures'].forEach((item){
          item['pdProtime'] = DateTime.parse(item['pdProtime']);
          item['pdDeltime'] = DateTime.parse(item['pdDeltime']);
          for (var bs in item['bs']) {
            match = Global.usrBusiness.business.indexOf(bs);
            temp.add(bs);
            if (match == -1) {
              temp.clear();
              break;
            }
          }
          String showStr = '';
          Global.business.forEach((items) {
            if (item['bs'].contains(items['bsId'])) {
              showStr = showStr.toString() + '【' + items['bsName'] + '】';
            }
          });
          item['show'] = showStr;
          show.addAll(temp);
          switch (item['pdStatus']) {
            case 400:
              {
                item['pdStatusTxt'] = "未包揽";
              }
              break;
            case 401:
              {
                item['pdStatusTxt'] = "进行中";
              }
              break;
            case 402:
              {
                item['pdStatusTxt'] = "已完成";
              }
              break;
            case 403:
              {
                item['pdStatusTxt'] = "工序关闭";
              }
              break;
            default:
              {
                print("Invalid choice");
              }
              break;
          }
        });
        Global.business.forEach((item) {
          if (show.contains(item['bsId'])) {
            showCard.add(item['bsName']);
          }
        });
        element['project']['show'] = List.from(showCard);
      });
    }
    return Global.matchingFriend;
  }
  Future<FindUserProjects> findUserProjects() async {
    Map<String,dynamic> formData = Map<String,dynamic>.from(
        {
          "token": Global.login.token,
        }
    );
    url = str + '/requirement/findUserProjects';
    Response r = await dio.post(url, data:formData);
    Global.findUserProjects = FindUserProjects.fromJson(r.data);
    //print(r.data);
    if(Global.findUserProjects.projects != null){
      Global.findUserProjects.projects.forEach((element) {

        element['pjReltime'] = DateTime.parse(element['pjReltime']).toLocal();
        element['pjProtime'] = DateTime.parse(element['pjProtime']).toLocal();
        //element['pjFintime'] = DateTime.parse(element['pjReltime']);
        element['pjDeltime'] = DateTime.parse(element['pjDeltime']);
        switch(element['pjStatus']){
          case 300: { element['pjStatusTxt'] = '未发布';}
          break;
          case 301: { element['pjStatusTxt'] = '已发布';}
          break;
          case 302: { element['pjStatusTxt'] = '正在进行';}
          break;
          case 303: { element['pjStatusTxt'] = '已完成';}
          break;
          case 304: { element['pjStatusTxt'] = '工程结束';}
          break;
          default: { print("Invalid choice"); }
          break;
        }
        int UndertakeCount = 0;
        element['procedures'].forEach((item){
          item['pdProtime'] = DateTime.parse(item['pdProtime']).toLocal();
          //print(item['pdProtime']);
          //item['pdFintime'] = DateTime.parse(item['pdFintime']);
          item['pdDeltime'] = DateTime.parse(item['pdDeltime']).toLocal();
          //print(item['pdDeltime']);

          switch(item['pdStatus']){
            case 400: { item['pdStatusTxt'] = '未包揽'; UndertakeCount = UndertakeCount + 1;}
            break;
            case 401: { item['pdStatusTxt'] = '进行中';}
            break;
            case 402: { item['pdStatusTxt'] = '已完成';}
            break;
            case 403: { item['pdStatusTxt'] = '工序关闭';}
            break;
            default: { print("Invalid choice"); }
            break;
          };
          item['bsTxt'] = '';
          Global.Checkbox.forEach((business) {
            if (item['bs'].contains(business['ID'])) {
              item['bsTxt'] = item['bsTxt'] + '【' + business['text'] + '】';
            }
          });
        });
        element['undertakeRate'] = UndertakeCount.toString() + '(未包揽)' + '/' + element['procedures'].length.toString();
      });
    }
    return Global.findUserProjects;
  }
  //更新工程进度、交工请求、更改交期
  Future<int> updateProgress(int procedureId, String schedule)async{
    Map<String,dynamic> formData = Map<String,dynamic>.from(
        {
          "token": Global.login.token,
          "procedureId": procedureId,
          "schedule": schedule
        }
    );
    url = str + '/requirement/modifySchedule';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  Future<int> modifyProcedures(int procedureId, DateTime pdDeltime)async{
    Map<String,dynamic> formData = Map<String,dynamic>.from(
        {
          "token": Global.login.token,
          "procedureId": procedureId,
          "pdDeltime": formatDate(pdDeltime, [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss])
        }
    );
    print(formData);
    url = str + '/requirement/modifyProcedures';
    Response r = await dio.post(url, data:formData);
    //print(r.data);
    return r.data['status'];
  }
  Future<int> completeApplication(int targetId, int pjId, int pdId)async{
    List formData = [
      {
        "token": Global.login.token
      },
      {
        "targetId":targetId,
        "pjId":pjId,
        "pdId":pdId,
      },
    ];
    print(formData);
    url = str + '/requirement/completeApplication';
    Response r = await dio.post(url, data:formData);
    Global.completeApplication = CompleteApplication.fromJson(r.data);
    print(Global.completeApplication.inform['aplState']);
    return Global.completeApplication.inform['aplState'];
  }
  Future<int> reminderApplication(int targetId, int pjId, int pdId)async{
    List formData = [
      {
        "token": Global.login.token
      },
      {
        "targetId":targetId,
        "pjId":pjId,
        "pdId":pdId,
      },
    ];
    print(formData);
    url = str + '/requirement/reminderApplication';
    Response r = await dio.post(url, data:formData);
    Global.reminderApplication = ReminderApplication.fromJson(r.data);
    print(Global.reminderApplication.inform['aplState']);
    return Global.reminderApplication.inform['aplState'];
  }
}